package com.villaday.idf;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Process;
import androidx.annotation.IdRes;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentManager;import androidx.fragment.app.FragmentTransaction;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.activity.BackHandlerHelper;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.base.BaseNoWhiteActivity;
import com.villaday.idf.custom.DownloadDialog;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.NewVersionDialog;
import com.villaday.idf.fragment.MessageFragment;
import com.villaday.idf.fragment.MineFragment;
import com.villaday.idf.fragment.OrdinaryVipFragment;
import com.villaday.idf.fragment2.FindHouse2Fragment;
import com.villaday.idf.fragment3.Home3vFragment;
import com.villaday.idf.fragment3.TeMaiFragment;
import com.villaday.idf.model.Locations_citiesEntity;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.model.UpgradeEntity;
import com.villaday.idf.service.ExampleUtil;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.DisplayCutoutUtil;
import com.villaday.idf.util.LogUtil;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.reactivex.functions.Consumer;


public class MainActivity extends BaseNoWhiteActivity implements OnClickListener, OkHttpUtil.OnProgressListener, RadioGroup.OnCheckedChangeListener, OkHttpUtil.OnDataListener
        , MineFragment.OnControlPageListener, OrdinaryVipFragment.OnViplPageListener, MessageFragment.Jump2Page, OrdinaryVipFragment.Jumps {

    @BindView(R.id.rg_mainTab)
    RadioGroup rgMainTab;
    @BindView(R.id.rb_mainTab0)
    RadioButton rbHome;

    @BindView(R.id.rb_mainTab2)
    RadioButton rb_mainTab2;


    private DownloadDialog downloadDialog;
    private String filePath;
    private Handler handler = new Handler();
    private boolean isForce = false;//是否强制升级

    private boolean isExit = false;//退出标识

    private int page;//要启动的Fragment的页数
    private int mark = -1;//输入邀请码弹出标识


    final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
    private FragmentManager fragmentManager;
    private Home3vFragment homeFragment;
    private MineFragment mineFragment;
    private TeMaiFragment teMaiFragment;
    private OrdinaryVipFragment ordinaryVipFragment;

    private Gson gson = new GsonBuilder().create();
    private String versionName;
    private MessageFragment messageFragment;

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private LoadingDialog loadingDialog;
    private String roleType;
    private int bournFragmentJumpType;
    private boolean isLocationed;
    private NewVersionDialog newDialog;

    private int homeType = 0;
    private Drawable drawable;
    private FindHouse2Fragment bournFragment=null;


    @Override
    protected int getViewResId() {
        return R.layout.activity_main;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void init() {
        RefreshtokenEntity.BodyBean roleInfo =
                SharedPreferencesUtil.getRoleInfo(this);
        roleType = roleInfo.getMember().getType();
        if ("0".equals(roleType)) {
            drawable = this.getResources().getDrawable(R.drawable.selector_main_tab2_putong);
            rb_mainTab2.setTextColor(getResources().getColorStateList(R.color.selector_color_red_black_check_putong));

        } else if ("1".equals(roleType)) {
            drawable = this.getResources().getDrawable(R.drawable.selector_main_tab2_vip);
            rb_mainTab2.setTextColor(getResources().getColorStateList(R.color.selector_color_red_black_check_vip));

        } else if ("2".equals(roleType)) {
            drawable = this.getResources().getDrawable(R.drawable.selector_main_tab2_svip);
            rb_mainTab2.setTextColor(getResources().getColorStateList(R.color.selector_color_red_black_check_svip));

        } else {
            drawable = this.getResources().getDrawable(R.drawable.selector_main_tab2_putong);
            rb_mainTab2.setTextColor(getResources().getColorStateList(R.color.selector_color_red_black_check_putong));
        }
        rb_mainTab2.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawable, null, null);
        mRxManager.on(getResources().getString(R.string.ChangeMainBotton_vip_dirwableAndColor), new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                if ("0".equals(s)) {
                    drawable = getResources().getDrawable(R.drawable.selector_main_tab2_putong);
                    rb_mainTab2.setTextColor(getResources().getColorStateList(R.color.selector_color_red_black_check_putong));

                } else if ("1".equals(s)) {
                    drawable = getResources().getDrawable(R.drawable.selector_main_tab2_vip);
                    rb_mainTab2.setTextColor(getResources().getColorStateList(R.color.selector_color_red_black_check_vip));

                } else if ("2".equals(s)) {
                    drawable = getResources().getDrawable(R.drawable.selector_main_tab2_svip);
                    rb_mainTab2.setTextColor(getResources().getColorStateList(R.color.selector_color_red_black_check_svip));

                } else {
                    drawable = getResources().getDrawable(R.drawable.selector_main_tab2_putong);
                    rb_mainTab2.setTextColor(getResources().getColorStateList(R.color.selector_color_red_black_check_putong));
                }
                rb_mainTab2.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawable, null, null);

            }
        });
        //更新 用户信息
        Map<String, Object> map = new HashMap<>();
        OkHttpUtil.postJson(this, Constant.URL.refresh_token, null, map, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                if (!TextUtils.isEmpty(json)) {
                    if (Constant.URL.refresh_token.equals(url)) { //刷新Token
                        LogeUtil.e("refresh_token", json);
                        RefreshtokenEntity refreshtoken = gson.fromJson(json, RefreshtokenEntity.class);
                        if (Constant.Strings.SUC.equals(refreshtoken.getCode())) {
                            //改变 主页bottom vip 图标及文字颜色
                            mRxManager.post(getResources().getString(R.string.ChangeMainBotton_vip_dirwableAndColor), refreshtoken.getBody().getMember().getType());

                            SharedPreferencesUtil.saveRoleInfo(MainActivity.this, json);
                            SharedPreferencesUtil.saveToken(MainActivity.this, refreshtoken.getBody().getToken());


                        }
                    }
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });


        //setLiuHai();
        LogeUtil.sHA1(this);
        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkPermissions();
        } else {
            upgrade();
            getLocation();
        }*/

        rgMainTab.setOnCheckedChangeListener(this);
        if (getIntent() == null || TextUtils.isEmpty(getIntent().getStringExtra("type"))) {
            rgMainTab.getChildAt(page).performClick();

        } else {
            if ("page/home".equals(getIntent().getStringExtra("type"))) {
                jump2Page(0, 0);

            } else if ("page/home/material".equals(getIntent().getStringExtra("type"))) {
                jump2Page(0, 0);

            } else if ("page/home/presell".equals(getIntent().getStringExtra("type"))) {

                if ("0".equals(roleType)) {
                    jump2Page(0, 0);

                } else {
                    jump2Page(0, 1);

                }
            } else if ("page/home/topic".equals(getIntent().getStringExtra("type"))) {
                if ("0".equals(roleType)) {
                    jump2Page(0, 1);

                } else {
                    jump2Page(0, 2);

                }

            } else if ("page/village".equals(getIntent().getStringExtra("type"))) {

                jump2Page(1, 0);
            } else if ("page/vip".equals(getIntent().getStringExtra("type"))) {

                jump2Page(2, 0);
            } else if ("page/member".equals(getIntent().getStringExtra("type"))) {

                jump2Page(4, 0);
            }
        }
        setAlias();


    }


    //定位
    private void getLocation() {
        if (isLocationed) {
            return;
        }
        isLocationed = true;
        loadingDialog = LoadingDialog.newInstance("定位中");
        loadingDialog.show(getFragmentManager(), "loading");
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setAddrType("all"); //返回的定位结果
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选，设置定位模式，默认高精度
//LocationMode.Hight_Accuracy：高精度；
//LocationMode. Battery_Saving：低功耗；
//LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("GCJ02");
//可选，设置返回经纬度坐标类型，默认GCJ02
//GCJ02：国测局坐标；
//BD09ll：百度经纬度坐标；
//BD09：百度墨卡托坐标；
//海外地区定位，无需设置坐标类型，统一返回WGS84类型坐标

        option.setScanSpan(1000);
//可选，设置发起定位请求的间隔，int类型，单位ms
//如果设置为0，则代表单次定位，即仅定位一次，默认为0
//如果设置非0，需设置1000ms以上才有效

        option.setIsNeedAddress(true);

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setNeedDeviceDirect(true);

        option.setOpenGps(true);
//可选，设置是否使用gps，默认false
//使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
//可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
//可选，定位SDK内部是一个service，并放到了独立进程。
//设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
//可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
//可选，V7.2版本新增能力
//如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位

        option.setEnableSimulateGps(false);
//可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
//mLocationClient为第二步初始化过的LocationClient对象
//需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
//更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
        mLocationClient.start();
//mLocationClient为第二步初始化过的LocationClient对象
//调用LocationClient的start()方法，便可发起定位请求

    }

    //// 这是来自 JPush Example 的设置别名的 Activity 里的代码。一般 App 的设置的调用入口，在任何方便的地方调用都可以。
    private void setAlias() {
        String alias = SharedPreferencesUtil.getUserInfo(this).getBody().getMember().getId();
        if (TextUtils.isEmpty(alias)) {
            //Toast.makeText(this, "用户设置别名失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!ExampleUtil.isValidTagAndAlias(alias)) {
            return;
        }

        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i("tag", logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i("tag", logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("tag", logs);
            }
            // ExampleUtil.showToast(logs, getApplicationContext());
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    // Log.d("tag", "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
                    Log.i("tag", "Unhandled msg - " + msg.what);
            }
        }
    };

    private void setLiuHai() {
        // adapt cutout
        //设置页面全屏显示
      /*  getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
                        View.SYSTEM_UI_FLAG_FULLSCREEN |
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);*/
        int pH = DisplayCutoutUtil.getStatusBarHeight(this);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        params.topMargin = pH;
        findViewById(R.id.rl_top).setLayoutParams(params);
    }

    //版本更新
    private void upgrade() {
        Map<String, String> map = new HashMap<>();
        map.put("force", "true");

        OkHttpUtil.getJSON(this, Constant.URL.upgrade, map, this);
    }


    private void downLoadApp(String versionName, String url) {
        downloadDialog = DownloadDialog.newInstance(PhoneUtil.getAppName(this) + versionName, isForce);
        downloadDialog.show(getFragmentManager(), "download");
        filePath = Environment.getExternalStorageDirectory() + "/Download/" + PhoneUtil.getAppName(this) +
                "_" + versionName + ".apk";
        Log.e("loge", "Download: " + filePath);
        OkHttpUtil.fileDownload(url, filePath, this, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {//下载完成

                LogeUtil.e("download" + json);
                TextView btnInstall = downloadDialog.getBtnInstall();
                btnInstall.setSelected(true);
                btnInstall.setText("安装");
                btnInstall.setClickable(true);
                btnInstall.setOnClickListener(MainActivity.this);
                jumpInstall();
            }

            @Override
            public void onFailure(String url, String error) {
            }
        });
    }


    @Override
    public void onClick(View view) {

        jumpInstall();
    }

    /**
     * 跳转到安装页面
     */
    private void jumpInstall() {
        File apkFile = new File(filePath);
        if (apkFile.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");

            } else {

                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);//给目标应用一个临时的授权
                Uri uriForFile = FileProvider.getUriForFile(this, PhoneUtil.getAppProcessName(this) + ".FileProvider", apkFile);
                intent.setDataAndType(uriForFile, "application/vnd.android.package-archive");

            }
            startActivity(intent);
            Process.killProcess(Process.myPid());

        }
    }

    @Override
    public void onProgress(final int rate) {
        ProgressBar pb = downloadDialog.getProgressBar();
        final TextView btnInstall = downloadDialog.getBtnInstall();
        if (pb != null) {
            pb.setProgress(rate);
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (btnInstall != null) {
                    btnInstall.setText("下载中(" + rate + "%)");
                    if (rate == 100) {
                        TextView btnInstall = downloadDialog.getBtnInstall();
                        btnInstall.setSelected(true);
                        btnInstall.setText("安装");
                        btnInstall.setClickable(true);
                        btnInstall.setOnClickListener(MainActivity.this);
                        jumpInstall();
                    }
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (!BackHandlerHelper.handleBackPress(this)) {

            if (isExit) {
//            System.exit(0);
                AppManager.getAppManager().AppExit(this);
            } else {
                ToastUtil.initToast(this, "再按一次退出" + PhoneUtil.getAppName(this));
                isExit = true;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isExit = false;
                    }
                }, 5000);//5秒内再按后退键真正退出
            }
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void checkPermissions() {
        List<String> permissionsNeeded = new ArrayList<String>();

        final List<String> permissionsList = new ArrayList<String>();
        if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))//存储
            permissionsNeeded.add("存储");
       /* if (!addPermission(permissionsList, Manifest.permission.CAMERA))//相机
            permissionsNeeded.add("相机");*/
        if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))//位置
            permissionsNeeded.add("位置");

        if (permissionsList.size() > 0) {
            if (permissionsNeeded.size() > 0) {
                // 需要去申请权限
                String message = "你需要申请 " + permissionsNeeded.get(0);
                for (int i = 1; i < permissionsNeeded.size(); i++) {
                    message = message + ", " + permissionsNeeded.get(i);

                }
                showMessageOKCancel(message + "等权限",
                        new DialogInterface.OnClickListener() {
                            @RequiresApi(api = Build.VERSION_CODES.M)
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                            }
                        });
                return;
            }
            requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
            return;
        }
        upgrade();
        getLocation();
        //可以操作
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean addPermission(List<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED&& !ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            permissionsList.add(permission);
            // Check for Rationale Option
            if (!shouldShowRequestPermissionRationale(permission))
                return false;
        }
        return true;
    }
    //如果所有权限被授权，依然回调onRequestPermissionsResult，我用hashmap让代码整洁便于阅读。

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
                Map<String, Integer> perms = new HashMap<String, Integer>();
                // 初始化所有权限
                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);//存储
                perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);//相机
                perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);//位置
                // Fill with results
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // 授权反馈成功
                if (perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                ) {
                    // 授权成功
                    upgrade();
                    getLocation();
                } else {
                    // 授权失败
                    upgrade();
                    getLocation();
                    Toast.makeText(MainActivity.this, "部分权限被拒绝，使用过程中可能会出现未知错误", Toast.LENGTH_SHORT)
                            .show();
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(MainActivity.this)
                .setMessage(message)
                .setPositiveButton("确定", okListener)
                .setNegativeButton("取消", null)
                .create()
                .show();
    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        if (fragmentManager == null) {
            fragmentManager = getSupportFragmentManager();

        }
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragments(transaction);

        switch (i) {
            case R.id.rb_mainTab0://首页
               /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkPermissions();
                } else {*/
                    upgrade();
                    getLocation();
              //  }


                page = 0;
                //homeFragment = null;
                if ("1".equals(SharedPreferencesUtil.getWechatPayType(this))) {
                    SharedPreferencesUtil.saveWechatPayType(this, "0");
                    //homeFragment.getdata();
                    homeFragment = null;
                }
                if (homeFragment == null) {
                    homeFragment = Home3vFragment.instance();
                    homeFragment.setOnJumpListener(new Home3vFragment.Jump() {
                        @Override
                        public void homeJump(int jumpType, int innerJumpType) {
                            if (jumpType == 4) {//我的跳转
                                rgMainTab.getChildAt(4).performClick();
                            } else if (jumpType == 1) {//特卖
                                bournFragmentJumpType = innerJumpType;
                                rgMainTab.getChildAt(1).performClick();
                            } else {
                                if (jumpType == 2) {
                                    mark = 2;
                                }
                                rgMainTab.getChildAt(jumpType).performClick();
                            }
                        }

                        @Override
                        public void homeJump(boolean isOk) {
                            if (!rbHome.isChecked()) {
                                setHomeChange();
                            }
                        }
                    });
                    homeFragment.setOnScrollWineListener(new Home3vFragment.onScrollHomeListener() {
                        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
                        @Override
                        public void onScroll(int scrollY, int height) {
                            if (scrollY < height) {
                                setHomeChange();
                            } else {
                                if (!homeFragment.isHidden() && homeFragment.isVisible() && rbHome.isChecked()) {
                                    homeType = 1;
                                    Drawable drawable = MainActivity.this.getResources().getDrawable(R.drawable.ic_main_top);
                                    rbHome.setText("回顶部");
                                    rbHome.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawable, null, null);
                                }
                            }

                        }
                    });


                    transaction.add(R.id.fl_main, homeFragment, "0");
                } else {
                    homeFragment.onRefreshState();
                    transaction.show(homeFragment);
                }
                break;
            case R.id.rb_mainTab1://特卖
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkPermissions();
                }
                page = 1;
                if (teMaiFragment == null) {
                    teMaiFragment = TeMaiFragment.instance();
                    teMaiFragment.setOnControlPageListener(this);
                    teMaiFragment.setJumps(this);
                    transaction.add(R.id.fl_main, teMaiFragment, "1");

                } else {
                  /*  bournFragment.setCity();
                    bournFragment.jump(bournFragmentJumpType);*/
                    transaction.show(teMaiFragment);


                }
                break;
            case R.id.rb_mainTab2://VIP
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkPermissions();
                }
                page = 2;
                if (ordinaryVipFragment == null) {
                    ordinaryVipFragment = OrdinaryVipFragment.instance();
                    ordinaryVipFragment.setOnControlPageListener(this);
                    ordinaryVipFragment.setJumps(this);
                    /**
                     * 防止对象未创建报空指针
                     */
                    transaction.add(R.id.fl_main, ordinaryVipFragment, "2");
                    if (mark != -1) {
                        ordinaryVipFragment.openInvitateDialog(1);
                        mark = -1;
                    }
                } else {
                    transaction.show(ordinaryVipFragment);
                    ordinaryVipFragment.checkToken();
                    if (mark != -1) {
                        ordinaryVipFragment.openInvitateDialog(2);
                        mark = -1;
                    }

                }


                break;
            case R.id.rb_mainTab3://消息中心
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkPermissions();
                }
                page = 3;
                if (messageFragment == null) {
                    messageFragment = MessageFragment.instance();
                    messageFragment.setjump2Page(this);
                    transaction.add(R.id.fl_main, messageFragment, "3");
                } else {
                    transaction.show(messageFragment);


                }


                break;
            case R.id.rb_mainTab4://我的
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkPermissions();
                }
                page = 4;
                if (mineFragment == null) {
                    mineFragment = MineFragment.instance();
                    mineFragment.setOnControlPageListener(this);
                    mineFragment.setjump2Page(this);

                    transaction.add(R.id.fl_main, mineFragment, "4");
                } else {
                    transaction.show(mineFragment);
                    setHomeChange();
                }
                break;

            case R.id.rb_mainTab5://目的地
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkPermissions();
                }
                page = 5;
                if (bournFragment == null) {
                    bournFragment = FindHouse2Fragment.instance(2);

                    bournFragment = FindHouse2Fragment.instance(2,false);



                    transaction.add(R.id.fl_main, bournFragment, "5");
                } else {
                    transaction.show(bournFragment);
                }



              /*  Intent intent = new Intent(this, JDMSBSActivity.class);
                intent.putExtra("type", 2);

                startActivity(intent);*/
                break;

        }
        transaction.commitAllowingStateLoss();
    }

    public void setHomeChange() {
        homeType = 0;
        Drawable drawable = MainActivity.this.getResources().getDrawable(R.drawable.selector_main_tab0);
        rbHome.setText("首页");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            rbHome.setCompoundDrawablesRelativeWithIntrinsicBounds(null, drawable, null, null);
        }
    }

    /**
     * 先隐藏所有Fragment
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
            setHomeChange();
        }
        if (mineFragment != null) {
            transaction.hide(mineFragment);
        }
        if (teMaiFragment != null) {
            transaction.hide(teMaiFragment);
        }
        if (ordinaryVipFragment != null) {
            transaction.hide(ordinaryVipFragment);
        }

        if (messageFragment != null) {
            transaction.hide(messageFragment);
        }

        if (bournFragment != null) {
            transaction.hide(bournFragment);
        }





       /*
        if (luckDrawFragment != null) {
            transaction.hide(luckDrawFragment);
        }
        if (masterFragment != null) {
            transaction.hide(masterFragment);
        }*/

    }

    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.locations_cities.equals(url)) {
                LogUtil.jLog().e(json);
                Locations_citiesEntity locations_citiesEntity = gson.fromJson(json, Locations_citiesEntity.class);
                if ("200".equals(locations_citiesEntity.getCode()) && locations_citiesEntity.getBody() != null) {

                    AppContext.currentCityidCurrent = locations_citiesEntity.getBody().getId();//当前城市id
                    AppContext.cityCurrent = locations_citiesEntity.getBody().getName();
                    //当前城市
                    AppContext.CityName = locations_citiesEntity.getBody().getName();
                    /*if (bournFragment != null) {
                        bournFragment.setCity();
                    }*/
                }
            } else if (Constant.URL.upgrade.equals(url)) {
                LogeUtil.e("upgrade", json);
                final UpgradeEntity upgradeEntity = gson.fromJson(json, UpgradeEntity.class);
                if ("200".equals(upgradeEntity.getCode())) {
                    isForce = false;
                    versionName = upgradeEntity.getBody().getBundleVersion();
                    String charStr = versionName.charAt(0) + "";
                    String ver = versionName;
                    if ("V".equals(charStr) || "v".equals(charStr)) {
                        ver = versionName.substring(1, versionName.length());
                    }
                    if ("V".equals(charStr)) {
                        isForce = true;
                    }
                    int isNeedUpdate = PhoneUtil.isNeedUpdate(PhoneUtil.getAppVersion(this), ver);
                    switch (isNeedUpdate) {
                        case 2://需要强制更新
                            isForce = true;
                        case 1://需要更新

                            String newContent = upgradeEntity.getBody().getMessage() + "</br>(建议在wifi下更新)";
                            if (newDialog != null && newDialog.isVisible()) {
                                return;
                            }
                            newDialog = NewVersionDialog.newInstance(ver,
                                    newContent.replace("</br>", "\n"), isForce == true ? "force" : "取消", "更新");
                            newDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                                @Override
                                public void onItemClick(View v) {
                                    downLoadApp(upgradeEntity.getBody().getBundleVersion(), upgradeEntity.getBody().getUrl());
                                }
                            });
                            newDialog.show(getFragmentManager());
                            break;
                    }
                }
            }
        }
    }

    @Override
    public void onFailure(String url, String error) {

    }

    @Override
    public void main() {
        rgMainTab.getChildAt(0).performClick();
    }


    @Override
    public void vipJump() {
        rgMainTab.getChildAt(0).performClick();
    }

    public void getCity() {
        OkHttpUtil.getJSON(this, Constant.URL.locations_cities, this);

    }

    @Override
    public void jump2Page(int page, int innerPage) {
        rgMainTab.getChildAt(page).performClick();

        if (page == 0) {//跳转首页
            if (homeFragment != null) {
                //homeFragment.jump2Page(innerPage);


            }

        } else if (page == 1) {//跳转目的地

        }

    }


    @Override
    public void orderJump(int jumpType, int innerJumpType) {
        if (jumpType == 4) {//我的跳转
            rgMainTab.getChildAt(4).performClick();
        } else if (jumpType == 1) {//找房源

            bournFragmentJumpType = innerJumpType;
            rgMainTab.getChildAt(1).performClick();

        }
    }


    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

            double latitude = location.getLatitude();    //获取纬度信息
            double longitude = location.getLongitude();    //获取经度信息
            float radius = location.getRadius();    //获取定位精度，默认值为0.0f

            String coorType = location.getCoorType();
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准

            int errorCode = location.getLocType();

            if (errorCode == 61 || errorCode == 161) {

                AppContext.latitude = latitude;
                AppContext.longitude = longitude;
                getCity();

                if (location.getAddrStr() != null && !location.getAddrStr().equals("")) {
                    if (location.getAddrStr().contains(location.getCity())) {
//                        String[] split = location.getAddrStr().split(location.getCity());
//                        if (split.length > 1) {
//                            homeFragment.setCity(location.getCity() + "·" + split[1]);
//                        } else {
//                            homeFragment.setCity(location.getCity() + "·" + (location.getStreet() == null ? "" : location.getStreet()));
//                        }
                    } else {
//                        homeFragment.setCity(location.getCity() + "·" + (location.getStreet() == null ? "" : location.getStreet()));
                    }
                    mLocationClient.stop();
                }

            }

            dismissLoading();
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
            LogeUtil.e("latitude" + latitude + "longitude" + longitude + "errorCode" + errorCode);

        }
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }

    }

    @OnClick({R.id.rb_mainTab0})
    public void btnOnclick(View view) {
        switch (view.getId()) {
            case R.id.rb_mainTab0:
                if (homeType == 1) {
                    homeFragment.setSkip(0);
                    homeType = 0;
                }
                break;


        }
    }

}


